<template>
  <div class="permission-control-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <el-icon class="title-icon">
            <Key />
          </el-icon>
          权限控制
        </h2>
        <p class="page-description">控制用户访问权限和功能授权</p>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon warning">
          <el-icon><Lock /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ permissionCount }}</div>
          <div class="stat-label">权限数量</div>
        </div>
      </div>
    </div>

    <!-- 权限管理区域 -->
    <div class="permission-management-container">
      <el-tabs v-model="activeTab" type="border-card" class="permission-tabs">
        <!-- 权限管理 -->
        <el-tab-pane label="权限管理" name="permission-management">
          <div class="tab-content">
            <div class="permission-management-header">
              <div class="header-left">
                <h4>权限列表管理</h4>
                <p class="header-description">管理系统中的所有权限，包括创建、查看和删除权限</p>
              </div>
              <div class="header-right">
                <el-button type="primary" @click="showCreatePermissionDialog">
                  <el-icon><Plus /></el-icon>
                  创建权限
                </el-button>
              </div>
            </div>

            <!-- 权限列表 -->
            <div class="permission-list-container">
              <el-table 
                :data="permissionList" 
                style="width: 100%" 
                v-loading="permissionLoading"
                element-loading-text="加载中..."
              >
                <el-table-column prop="name" label="权限名称" min-width="150">
                  <template #default="scope">
                    <div class="permission-name">
                      <el-icon class="permission-icon"><Lock /></el-icon>
                      <span>{{ scope.row.name }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="code" label="权限编码" min-width="200">
                  <template #default="scope">
                    <el-tag type="info" size="small" class="permission-code-tag">
                      {{ scope.row.code }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="权限描述" min-width="200" show-overflow-tooltip />
                <el-table-column label="操作" width="150" align="center">
                  <template #default="scope">
                    <div class="action-buttons">
                      <el-button type="danger" size="small" @click="deletePermission(scope.row)">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <!-- 角色权限分配 -->
        <el-tab-pane label="角色权限分配" name="role-permission">
          <div class="tab-content">
            <div class="role-selection">
              <el-select v-model="selectedRole" placeholder="请选择角色" @change="handleRoleChange">
                <el-option
                  v-for="role in roleList"
                  :key="role.roleId"
                  :label="role.name"
                  :value="role.roleId"
                />
              </el-select>
              <el-button type="primary" @click="saveRolePermissions" :loading="savingPermissions">
                <el-icon><Check /></el-icon>
                保存权限
              </el-button>
            </div>
            
                          <div class="permission-tree-container">
                <div class="tree-header">
                  <div class="tree-header-left">
                    <h4>菜单权限分配</h4>
                    <div class="permission-stats">
                      <span class="stat-item">
                        <el-icon><Check /></el-icon>
                        已选: {{ checkedMenuKeys.length }}
                      </span>
                      <span class="stat-item">
                        <el-icon><Menu /></el-icon>
                        总计: {{ getAllMenuIds(menuPermissionData).length }}
                      </span>
                    </div>
                  </div>
                  <div class="tree-actions">
                    <el-button size="small" @click="checkAllMenus">
                      <el-icon><Check /></el-icon>
                      全选
                    </el-button>
                    <el-button size="small" @click="uncheckAllMenus">
                      <el-icon><Close /></el-icon>
                      全不选
                    </el-button>
                  </div>
                </div>
              
              <el-tree
                :key="treeKey"
                ref="menuPermissionTree"
                :data="menuPermissionData"
                :props="menuTreeProps"
                node-key="id"
                show-checkbox
                :default-checked-keys="checkedMenuKeys"
                :expanded-keys="expandedMenuKeys"
                class="permission-tree"
                @check="handleCheck"
                @expand="handleExpand"
                @collapse="handleCollapse"
                :check-strictly="false"
                :expand-on-click-node="false"
                :highlight-current="true"
              >
                                  <template #default="{ node, data }">
                    <div class="tree-node-content">
                      <div class="node-left">
                        <i :class="data.icon || 'el-icon-menu'" class="menu-icon"></i>
                        <div class="node-info">
                          <span class="menu-name">{{ data.name }}</span>
                          <span class="menu-path">{{ data.path }}</span>
                          <span v-if="data.description" class="menu-description">{{ data.description }}</span>
                        </div>
                      </div>
                      <div class="node-right">
                        <el-tag v-if="data.type" size="small" :type="data.type === 'page' ? 'primary' : 'success'">
                          {{ data.type === 'page' ? '页面' : '按钮' }}
                        </el-tag>
                        <el-tag v-if="data.permissionCode" size="small" type="info" class="permission-code">
                          {{ data.permissionCode }}
                        </el-tag>
                      </div>
                    </div>
                  </template>
              </el-tree>
            </div>
          </div>
        </el-tab-pane>

        <!-- 用户权限测试 -->
        <el-tab-pane label="用户权限测试" name="user-test">
          <div class="tab-content">
            <div class="test-section">
              <h4>模拟用户登录</h4>
              <div class="user-simulation">
                <el-select v-model="testUser" placeholder="请选择测试用户" @change="handleUserChange">
                  <el-option
                    v-for="user in testUserList"
                    :key="user.id"
                    :label="user.name"
                    :value="user.id"
                  />
                </el-select>
                <el-button type="success" @click="simulateLogin">
                  <el-icon><User /></el-icon>
                  模拟登录
                </el-button>
              </div>
              
              <div v-if="currentTestUser" class="user-info">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="用户名">{{ currentTestUser.name }}</el-descriptions-item>
                  <el-descriptions-item label="角色">{{ currentTestUser.role }}</el-descriptions-item>
                  <el-descriptions-item label="可访问菜单">{{ currentTestUser.menuCount }}个</el-descriptions-item>
                  <el-descriptions-item label="可操作按钮">{{ currentTestUser.buttonCount }}个</el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
            
            <div class="test-section">
              <h4>权限验证测试</h4>
              <div class="permission-test">
                <el-button 
                  v-for="test in permissionTests" 
                  :key="test.id"
                  :type="test.hasPermission ? 'primary' : 'info'"
                  :disabled="!test.hasPermission"
                  @click="testPermission(test)"
                  class="test-button"
                  :class="{ 'test-button-clicked': test.isClicked }"
                >
                  <el-icon><component :is="test.icon" /></el-icon>
                  {{ test.name }}
                </el-button>
              </div>
            </div>
            
            <div class="test-section">
              <h4>菜单访问测试</h4>
              <div class="menu-test">
                <el-card 
                  v-for="menu in accessibleMenus" 
                  :key="menu.id"
                  class="menu-card"
                  :class="{ 'disabled': !menu.hasPermission }"
                >
                  <div class="menu-card-header">
                    <i :class="menu.icon" class="menu-card-icon"></i>
                    <span class="menu-card-title">{{ menu.name }}</span>
                    <el-tag v-if="!menu.hasPermission" type="danger" size="small">无权限</el-tag>
                  </div>
                  <div class="menu-card-content">
                    <p class="menu-path">{{ menu.path }}</p>
                    <div class="menu-actions">
                      <el-button size="small" @click="accessMenu(menu)" :disabled="!menu.hasPermission">
                        访问页面
                      </el-button>
                      <el-button size="small" @click="viewMenuDetail(menu)">
                        查看详情
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </div>
        </el-tab-pane>


      </el-tabs>
    </div>

    <!-- 创建权限对话框 -->
    <el-dialog
      v-model="createPermissionVisible"
      title="创建新权限"
      width="500px"
      class="create-permission-dialog"
    >
      <el-form
        ref="createPermissionFormRef"
        :model="createPermissionForm"
        :rules="createPermissionRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="createPermissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="createPermissionForm.code" placeholder="例如: user:create" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input
            v-model="createPermissionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="createPermissionVisible = false">取消</el-button>
          <el-button type="primary" @click="createPermission" :loading="creatingPermission">
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Check, User, Close, 
  Edit, Delete, Plus, Search, Setting,
  Document, Folder, Lock, Key, Star, Menu
} from '@element-plus/icons-vue'
import { roleApi } from '@/api'
import { permissionApi } from '@/api/permission'

console.log('PermissionControl组件已加载')

// 响应式数据
const activeTab = ref('permission-management')
const selectedRole = ref('')
const testUser = ref('')
const savingPermissions = ref(false)
const menuPermissionTree = ref(null)

// 权限管理相关数据
const permissionList = ref([])
const permissionLoading = ref(false)
const createPermissionVisible = ref(false)
const creatingPermission = ref(false)
const createPermissionFormRef = ref(null)


// 创建权限表单
const createPermissionForm = ref({
  name: '',
  code: '',
  description: ''
})

// 创建权限表单验证规则
const createPermissionRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-z]+:[a-z]+(:[a-z]+)*$/, message: '权限编码格式为 module:action 或 module:action:subaction', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '权限描述不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 统计数据
const permissionCount = ref(0)

// 角色列表
const roleList = ref([])

// 菜单权限数据 - 基于实际系统功能
const menuPermissionData = ref([
  {
    id: 'dashboard',
    name: '仪表板',
    path: '/dashboard',
    icon: 'el-icon-data-board',
    type: 'page',
    permissionCode: 'dashboard:view',
    description: '系统概览和统计信息'
  },
  {
    id: 'user',
    name: '用户管理',
    path: '/user',
    icon: 'el-icon-user',
    type: 'page',
    permissionCode: 'user:view',
    description: '用户信息管理',
    children: [
      {
        id: 'user:list',
        name: '用户列表',
        path: '/user/list',
        icon: 'el-icon-s-custom',
        type: 'page',
        permissionCode: 'user:list:view',
        description: '查看所有用户列表',
        children: [
          { 
            id: 'user:list:view', 
            name: '查看用户', 
            type: 'button',
            permissionCode: 'user:list:view',
            description: '查看用户列表'
          },
          { 
            id: 'user:list:export', 
            name: '导出用户', 
            type: 'button',
            permissionCode: 'user:list:export',
            description: '导出用户数据'
          }
        ]
      },
      {
        id: 'user:create',
        name: '创建用户',
        path: '/user/create',
        icon: 'el-icon-plus',
        type: 'page',
        permissionCode: 'user:create',
        description: '创建新用户',
        children: [
          { 
            id: 'user:create:submit', 
            name: '提交创建', 
            type: 'button',
            permissionCode: 'user:create:submit',
            description: '提交用户创建表单'
          }
        ]
      },
      {
        id: 'user:edit',
        name: '编辑用户',
        path: '/user/edit',
        icon: 'el-icon-edit',
        type: 'page',
        permissionCode: 'user:edit',
        description: '编辑用户信息',
        children: [
          { 
            id: 'user:edit:submit', 
            name: '保存修改', 
            type: 'button',
            permissionCode: 'user:edit:submit',
            description: '保存用户信息修改'
          },
          { 
            id: 'user:edit:delete', 
            name: '删除用户', 
            type: 'button',
            permissionCode: 'user:edit:delete',
            description: '删除用户账户'
          }
        ]
      }
    ]
  },
  {
    id: 'role',
    name: '角色管理',
    path: '/role',
    icon: 'el-icon-s-check',
    type: 'page',
    permissionCode: 'role:view',
    description: '角色权限管理',
    children: [
      {
        id: 'role:list',
        name: '角色列表',
        path: '/role/list',
        icon: 'el-icon-s-order',
        type: 'page',
        permissionCode: 'role:list:view',
        description: '查看所有角色',
        children: [
          { 
            id: 'role:list:view', 
            name: '查看角色', 
            type: 'button',
            permissionCode: 'role:list:view',
            description: '查看角色列表'
          },
          { 
            id: 'role:list:export', 
            name: '导出角色', 
            type: 'button',
            permissionCode: 'role:list:export',
            description: '导出角色数据'
          }
        ]
      },
      {
        id: 'role:create',
        name: '创建角色',
        path: '/role/create',
        icon: 'el-icon-plus',
        type: 'page',
        permissionCode: 'role:create',
        description: '创建新角色',
        children: [
          { 
            id: 'role:create:submit', 
            name: '提交创建', 
            type: 'button',
            permissionCode: 'role:create:submit',
            description: '提交角色创建表单'
          }
        ]
      },
      {
        id: 'role:edit',
        name: '编辑角色',
        path: '/role/edit',
        icon: 'el-icon-edit',
        type: 'page',
        permissionCode: 'role:edit',
        description: '编辑角色信息',
        children: [
          { 
            id: 'role:edit:submit', 
            name: '保存修改', 
            type: 'button',
            permissionCode: 'role:edit:submit',
            description: '保存角色信息修改'
          },
          { 
            id: 'role:edit:delete', 
            name: '删除角色', 
            type: 'button',
            permissionCode: 'role:edit:delete',
            description: '删除角色'
          }
        ]
      }
    ]
  },
  {
    id: 'permission',
    name: '权限管理',
    path: '/permission',
    icon: 'el-icon-lock',
    type: 'page',
    permissionCode: 'permission:view',
    description: '权限控制管理',
    children: [
      {
        id: 'permission:control',
        name: '权限控制',
        path: '/permission/control',
        icon: 'el-icon-key',
        type: 'page',
        permissionCode: 'permission:control:view',
        description: '权限分配控制',
        children: [
          { 
            id: 'permission:control:assign', 
            name: '分配权限', 
            type: 'button',
            permissionCode: 'permission:control:assign',
            description: '为角色分配权限'
          },
          { 
            id: 'permission:control:view', 
            name: '查看权限', 
            type: 'button',
            permissionCode: 'permission:control:view',
            description: '查看角色权限'
          }
        ]
      }
    ]
  },
  {
    id: 'file',
    name: '文件管理',
    path: '/file',
    icon: 'el-icon-folder',
    type: 'page',
    permissionCode: 'file:view',
    description: '文件上传下载管理',
    children: [
      {
        id: 'file:list',
        name: '文件列表',
        path: '/file/list',
        icon: 'el-icon-s-order',
        type: 'page',
        permissionCode: 'file:list:view',
        description: '查看所有文件',
        children: [
          { 
            id: 'file:list:view', 
            name: '查看文件', 
            type: 'button',
            permissionCode: 'file:list:view',
            description: '查看文件列表'
          },
          { 
            id: 'file:list:download', 
            name: '下载文件', 
            type: 'button',
            permissionCode: 'file:list:download',
            description: '下载文件'
          }
        ]
      },
      {
        id: 'file:upload',
        name: '文件上传',
        path: '/file/upload',
        icon: 'el-icon-upload',
        type: 'page',
        permissionCode: 'file:upload',
        description: '上传新文件',
        children: [
          { 
            id: 'file:upload:submit', 
            name: '提交上传', 
            type: 'button',
            permissionCode: 'file:upload:submit',
            description: '提交文件上传'
          }
        ]
      },
      {
        id: 'file:delete',
        name: '删除文件',
        path: '/file/delete',
        icon: 'el-icon-delete',
        type: 'page',
        permissionCode: 'file:delete',
        description: '删除文件',
        children: [
          { 
            id: 'file:delete:confirm', 
            name: '确认删除', 
            type: 'button',
            permissionCode: 'file:delete:confirm',
            description: '确认删除文件'
          }
        ]
      }
    ]
  },
  {
    id: 'system',
    name: '系统管理',
    path: '/system',
    icon: 'el-icon-setting',
    type: 'page',
    permissionCode: 'system:view',
    description: '系统设置和配置',
    children: [
      {
        id: 'system:settings',
        name: '系统设置',
        path: '/system/settings',
        icon: 'el-icon-s-tools',
        type: 'page',
        permissionCode: 'system:settings:view',
        description: '系统参数配置',
        children: [
          { 
            id: 'system:settings:view', 
            name: '查看设置', 
            type: 'button',
            permissionCode: 'system:settings:view',
            description: '查看系统设置'
          },
          { 
            id: 'system:settings:edit', 
            name: '修改设置', 
            type: 'button',
            permissionCode: 'system:settings:edit',
            description: '修改系统设置'
          }
        ]
      },
      {
        id: 'system:log',
        name: '日志管理',
        path: '/system/log',
        icon: 'el-icon-document',
        type: 'page',
        permissionCode: 'system:log:view',
        description: '系统日志查看',
        children: [
          { 
            id: 'system:log:view', 
            name: '查看日志', 
            type: 'button',
            permissionCode: 'system:log:view',
            description: '查看系统日志'
          },
          { 
            id: 'system:log:export', 
            name: '导出日志', 
            type: 'button',
            permissionCode: 'system:log:export',
            description: '导出系统日志'
          }
        ]
      }
    ]
  }
])

// 树配置
const menuTreeProps = {
  children: 'children',
  label: 'name'
}

// 选中的菜单权限
const checkedMenuKeys = ref([])
const expandedMenuKeys = ref([])
const treeKey = ref(0) // 用于强制重新渲染树组件

// 测试用户列表
const testUserList = ref([
  { id: 1, name: '张三', role: '超级管理员', permissions: ['all'] },
  { id: 2, name: '李四', role: '普通管理员', permissions: ['user:view', 'user:edit', 'content:view', 'content:edit'] },
  { id: 3, name: '王五', role: '内容编辑', permissions: ['content:view', 'content:edit'] },
  { id: 4, name: '赵六', role: '访客用户', permissions: ['content:view'] }
])

// 当前测试用户
const currentTestUser = ref(null)

// 权限测试列表
const permissionTests = ref([
  { id: 1, name: '创建用户', icon: 'Plus', hasPermission: false, isClicked: false },
  { id: 2, name: '编辑用户', icon: 'Edit', hasPermission: false, isClicked: false },
  { id: 3, name: '删除用户', icon: 'Delete', hasPermission: false, isClicked: false },
  { id: 4, name: '查看日志', icon: 'Document', hasPermission: false, isClicked: false },
  { id: 5, name: '系统设置', icon: 'Setting', hasPermission: false, isClicked: false },
  { id: 6, name: '创建文章', icon: 'Edit', hasPermission: false, isClicked: false },
  { id: 7, name: '上传文件', icon: 'Folder', hasPermission: false, isClicked: false },
  { id: 8, name: '分配权限', icon: 'Key', hasPermission: false, isClicked: false }
])

// 可访问菜单
const accessibleMenus = ref([])



// 角色权限映射 - 根据角色名称映射权限
const rolePermissions = {
  '超级管理员': ['all'],
  '管理员': ['dashboard:view', 'user:view', 'user:list:view', 'user:list:export', 'role:view', 'role:list:view', 'file:view', 'file:list:view', 'system:view', 'system:log:view'],
  '普通用户': ['dashboard:view', 'file:view', 'file:list:view'],
  '访客用户': ['dashboard:view']
}

// 菜单权限映射 - 基于新的权限代码结构
const menuPermissions = {
  'dashboard:view': ['dashboard'],
  'user:view': ['user', 'user:list', 'user:create', 'user:edit'],
  'user:list:view': ['user:list', 'user:list:view'],
  'user:list:export': ['user:list:export'],
  'user:create': ['user:create', 'user:create:submit'],
  'user:edit': ['user:edit', 'user:edit:submit', 'user:edit:delete'],
  'role:view': ['role', 'role:list', 'role:create', 'role:edit'],
  'role:list:view': ['role:list', 'role:list:view'],
  'role:list:export': ['role:list:export'],
  'role:create': ['role:create', 'role:create:submit'],
  'role:edit': ['role:edit', 'role:edit:submit', 'role:edit:delete'],
  'permission:view': ['permission', 'permission:control'],
  'permission:control:view': ['permission:control', 'permission:control:view'],
  'permission:control:assign': ['permission:control:assign'],
  'file:view': ['file', 'file:list', 'file:upload', 'file:delete'],
  'file:list:view': ['file:list', 'file:list:view'],
  'file:list:download': ['file:list:download'],
  'file:upload': ['file:upload', 'file:upload:submit'],
  'file:delete': ['file:delete', 'file:delete:confirm'],
  'system:view': ['system', 'system:settings', 'system:log'],
  'system:settings:view': ['system:settings', 'system:settings:view'],
  'system:settings:edit': ['system:settings:edit'],
  'system:log:view': ['system:log', 'system:log:view'],
  'system:log:export': ['system:log:export']
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const response = await roleApi.getRoles()
    roleList.value = response.data || []
  } catch (error) {
    ElMessage.error('获取角色列表失败：' + (error.response?.data?.message || error.message))
  }
}

// 处理角色变化
const handleRoleChange = (roleId) => {
  // 根据角色ID找到角色名称
  const selectedRoleData = roleList.value.find(role => role.roleId === roleId)
  if (selectedRoleData) {
    // 根据角色名称加载对应的权限
    const permissions = rolePermissions[selectedRoleData.name] || []
    loadRolePermissions(permissions)
  }
}

// 加载角色权限
const loadRolePermissions = (permissions) => {
  // 根据权限设置选中的菜单
  const checkedKeys = []
  const expandedKeys = []
  
  permissions.forEach(permission => {
    const menuIds = menuPermissions[permission] || []
    checkedKeys.push(...menuIds)
  })
  
  // 去重
  const uniqueCheckedKeys = [...new Set(checkedKeys)]
  
  checkedMenuKeys.value = uniqueCheckedKeys
  expandedMenuKeys.value = expandedKeys
}

// 保存角色权限
const saveRolePermissions = async () => {
  if (!selectedRole.value) {
    ElMessage.warning('请先选择角色')
    return
  }
  
  savingPermissions.value = true
  try {
    // 获取选中的权限
    const checkedNodes = menuPermissionTree.value.getCheckedNodes()
    const halfCheckedNodes = menuPermissionTree.value.getHalfCheckedNodes()
    
    // 获取选中的权限ID列表
    const selectedPermissionIds = checkedNodes.map(node => node.id)
    
    // 调用后端API保存权限
    await roleApi.assignPermissionsToRoleByIds(selectedRole.value, selectedPermissionIds)
    
    ElMessage.success('权限保存成功！')
  } catch (error) {
    ElMessage.error('权限保存失败：' + (error.response?.data?.message || error.message))
  } finally {
    savingPermissions.value = false
  }
}



// 全选菜单
const checkAllMenus = async () => {
  try {
    await nextTick()
    if (menuPermissionTree.value) {
      const allIds = getAllMenuIds(menuPermissionData.value)
      // 使用树组件的方法选中所有节点
      menuPermissionTree.value.setCheckedKeys(allIds)
      checkedMenuKeys.value = allIds
      ElMessage.success('全选菜单成功')
    }
  } catch (error) {
    ElMessage.error('全选菜单失败')
  }
}

// 全不选菜单
const uncheckAllMenus = async () => {
  try {
    await nextTick()
    if (menuPermissionTree.value) {
      // 使用树组件的方法取消选中所有节点
      menuPermissionTree.value.setCheckedKeys([])
      checkedMenuKeys.value = []
      ElMessage.success('取消全选菜单成功')
    }
  } catch (error) {
    ElMessage.error('取消全选菜单失败')
  }
}

// 获取所有菜单ID
const getAllMenuIds = (menus) => {
  const ids = []
  const traverse = (items) => {
    items.forEach(item => {
      ids.push(item.id)
      if (item.children && item.children.length > 0) {
        traverse(item.children)
      }
    })
  }
  traverse(menus)
  return ids
}

// 处理树节点选中事件
const handleCheck = (data, checkedInfo) => {
  // 更新选中的菜单键
  checkedMenuKeys.value = checkedInfo.checkedKeys
}

// 处理树节点展开事件
const handleExpand = (data, expandedInfo) => {
  // 更新展开的菜单键
  expandedMenuKeys.value = expandedInfo.expandedKeys
}

// 处理树节点折叠事件
const handleCollapse = (data, collapsedInfo) => {
  // 更新展开的菜单键
  expandedMenuKeys.value = collapsedInfo.expandedKeys
}

// 处理用户变化
const handleUserChange = (userId) => {
  // 用户选择处理
}

// 模拟用户登录
const simulateLogin = () => {
  if (!testUser.value) {
    ElMessage.warning('请先选择测试用户')
    return
  }
  
  const user = testUserList.value.find(u => u.id === testUser.value)
  if (user) {
    currentTestUser.value = {
      ...user,
      menuCount: getMenuCount(user.permissions),
      buttonCount: getButtonCount(user.permissions)
    }
    
    // 更新权限测试
    updatePermissionTests(user.permissions)
    
    // 更新可访问菜单
    updateAccessibleMenus(user.permissions)
    
    ElMessage.success(`模拟登录成功：${user.name}`)
  }
}

// 获取菜单数量
const getMenuCount = (permissions) => {
  if (permissions.includes('all')) return menuCount.value
  return permissions.filter(p => p.includes(':view')).length
}

// 获取按钮数量
const getButtonCount = (permissions) => {
  if (permissions.includes('all')) return permissionCount.value
  return permissions.filter(p => p.includes(':edit') || p.includes(':create') || p.includes(':delete')).length
}

// 更新权限测试
const updatePermissionTests = (permissions) => {
  permissionTests.value.forEach(test => {
    test.hasPermission = permissions.includes('all') || 
                        permissions.some(p => test.name.toLowerCase().includes(p.split(':')[0]))
  })
}

// 更新可访问菜单
const updateAccessibleMenus = (permissions) => {
  accessibleMenus.value = menuPermissionData.value.map(menu => ({
    ...menu,
    hasPermission: permissions.includes('all') || 
                  permissions.some(p => menu.name.toLowerCase().includes(p.split(':')[0]))
  }))
}

// 测试权限
const testPermission = (test) => {
  if (test.hasPermission) {
    ElMessage.success(`权限测试通过：${test.name}`)
    // 添加选中状态的视觉反馈
    test.isClicked = true
    setTimeout(() => {
      test.isClicked = false
    }, 500)
  } else {
    ElMessage.error(`权限不足：${test.name}`)
  }
}

// 访问菜单
const accessMenu = (menu) => {
  if (menu.hasPermission) {
    ElMessage.success(`正在访问：${menu.name}`)
  } else {
    ElMessage.error(`无权限访问：${menu.name}`)
  }
}

// 查看菜单详情
const viewMenuDetail = (menu) => {
  ElMessage.info(`菜单详情：${menu.name} - ${menu.path}`)
}

// 权限管理相关方法

// 获取权限列表
const getPermissionList = async () => {
  permissionLoading.value = true
  try {
    const response = await permissionApi.getPermissions()
    
    // 检查响应数据结构
    if (response && Array.isArray(response)) {
      permissionList.value = response
      permissionCount.value = response.length
    } else if (response && response.data && Array.isArray(response.data)) {
      permissionList.value = response.data
      permissionCount.value = response.data.length
    } else {
      permissionList.value = []
      permissionCount.value = 0
      
      // 如果后端没有数据，使用模拟数据
      if (!response || (Array.isArray(response) && response.length === 0)) {
        permissionList.value = [
          {
            name: '文件上传',
            code: 'file:Create',
            description: '允许用户上传文件到系统'
          },
          {
            name: '文件下载',
            code: 'file:Read',
            description: '允许用户下载系统中的文件'
          },
          {
            name: '文件删除',
            code: 'file:Delete',
            description: '允许用户删除系统中的文件'
          },
          {
            name: '用户管理',
            code: 'user:Manage',
            description: '允许管理用户账户信息'
          },
          {
            name: '角色管理',
            code: 'role:Manage',
            description: '允许管理系统角色和权限'
          },
          {
            name: '权限管理',
            code: 'permission:Manage',
            description: '允许管理系统权限配置'
          }
        ]
        permissionCount.value = permissionList.value.length
      }
    }
  } catch (error) {
    // 根据错误类型给出不同的提示
    if (error.response?.status === 401) {
      ElMessage.error('权限不足，请先登录或联系管理员')
    } else if (error.response?.status === 403) {
      ElMessage.error('没有查看权限的权限，请联系管理员')
    } else {
      ElMessage.error('获取权限列表失败：' + (error.response?.data?.message || error.message))
    }
    
    permissionList.value = []
    permissionCount.value = 0
  } finally {
    permissionLoading.value = false
  }
}

// 显示创建权限对话框
const showCreatePermissionDialog = () => {
  createPermissionForm.value = {
    name: '',
    code: '',
    description: ''
  }
  createPermissionVisible.value = true
}

// 创建权限
const createPermission = async () => {
  if (!createPermissionFormRef.value) return
  
  try {
    await createPermissionFormRef.value.validate()
    creatingPermission.value = true
    
    const permissionData = {
      name: createPermissionForm.value.name,
      resource: createPermissionForm.value.code.split(':')[0],
      actionValue: 1, // 默认值，实际应该根据权限类型设置
      description: createPermissionForm.value.description
    }
    
    await permissionApi.createPermission(permissionData)
    
    ElMessage.success('权限创建成功')
    createPermissionVisible.value = false
    
    // 重新加载权限列表
    await getPermissionList()
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error('创建权限失败：' + error.response.data.message)
    } else {
      ElMessage.error('创建权限失败：' + error.message)
    }
  } finally {
    creatingPermission.value = false
  }
}



// 删除权限
const deletePermission = async (permission) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${permission.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await permissionApi.deletePermission(permission.id)
    ElMessage.success('权限删除成功')
    
    // 重新加载权限列表
    await getPermissionList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除权限失败：' + (error.response?.data?.message || error.message))
    }
  }
}

// 初始化数据
onMounted(async () => {
  try {
    // 获取权限列表
    await getPermissionList()
    
    // 获取角色列表
    await getRoleList()
    
    // 等待树组件渲染完成
    await nextTick()
    
    // 默认选择第一个角色
    if (roleList.value.length > 0) {
      selectedRole.value = roleList.value[0].roleId
      handleRoleChange(selectedRole.value)
    }
  } catch (error) {
    ElMessage.error('初始化失败：' + error.message)
  }
})
</script>

<style scoped>
.permission-control-container {
  width: 100%;
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
  background: #f5f7fa;
  margin: 0;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.header-left {
  flex: 1;
  margin-right: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 1.8rem;
  color: #303133;
  margin: 0 0 5px 0;
}

.title-icon {
  margin-right: 10px;
  color: #409eff;
  font-size: 1.5rem;
}

.page-description {
  color: #909399;
  font-size: 0.9rem;
  margin: 0;
}

.stats-cards {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 15px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.admin {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.deleted {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.warning {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.permission-management-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.permission-tabs {
  border-radius: 0;
  overflow: hidden;
  box-shadow: none;
}

.tab-content {
  padding: 20px;
}

.role-selection {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  align-items: center;
}

.permission-tree-container {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
  margin-top: 20px;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.tree-header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tree-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.permission-stats {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #606266;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-item .el-icon {
  font-size: 12px;
  color: #409eff;
}

.tree-actions {
  display: flex;
  gap: 8px;
}

.permission-tree {
  padding: 20px;
  max-height: 500px;
  overflow-y: auto;
}

.tree-node-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  flex: 1;
  padding: 4px 0;
}

.node-left {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.node-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.menu-icon {
  font-size: 16px;
  color: #409eff;
  width: 20px;
  text-align: center;
  flex-shrink: 0;
}

.menu-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.menu-path {
  color: #909399;
  font-size: 12px;
  font-family: monospace;
}

.menu-description {
  color: #606266;
  font-size: 11px;
  font-style: italic;
}

.node-right {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-shrink: 0;
}

.permission-code {
  font-family: monospace;
  font-size: 10px;
}

/* 权限管理样式 */
.permission-management-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.permission-management-header .header-left h4 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.permission-management-header .header-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.permission-list-container {
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
}

.permission-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-icon {
  color: #409eff;
  font-size: 16px;
}

.permission-code-tag {
  font-family: monospace;
  font-size: 11px;
}

.action-buttons {
  display: flex;
  gap: 6px;
  justify-content: center;
}

.action-buttons .el-button {
  height: 28px;
  padding: 0 8px;
  font-size: 12px;
}

/* 创建权限对话框样式 */
.create-permission-dialog {
  border-radius: 12px;
}

.create-permission-dialog :deep(.el-dialog__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  border-radius: 12px 12px 0 0;
}

.create-permission-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.create-permission-dialog :deep(.el-dialog__footer) {
  background: #f8f9fa;
  border-top: 1px solid #e4e7ed;
  border-radius: 0 0 12px 12px;
  padding: 15px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.test-section {
  margin-bottom: 30px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.test-section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.user-simulation {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  align-items: center;
}

.user-info {
  margin-bottom: 20px;
}

.permission-test {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
  margin-bottom: 20px;
}

.test-button {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
}

.test-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.test-button:active {
  transform: translateY(0);
}

.test-button-clicked {
  animation: buttonClick 0.5s ease;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
  transform: scale(0.95);
}

@keyframes buttonClick {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.95);
  }
  100% {
    transform: scale(1);
  }
}

.menu-test {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.menu-card {
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  border-radius: 8px;
}

.menu-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.menu-card.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.menu-card.disabled:hover {
  transform: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-color: #e4e7ed;
}

.menu-card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.menu-card-icon {
  font-size: 18px;
  color: #667eea;
}

.menu-card-title {
  font-weight: 600;
  color: #2c3e50;
  flex: 1;
}

.menu-card-content {
  padding-top: 10px;
}

.menu-path {
  color: #7f8c8d;
  font-size: 12px;
  margin-bottom: 10px;
}

.menu-actions {
  display: flex;
  gap: 8px;
}



/* 深度样式修改 */
:deep(.el-tabs__header) {
  background: #f8f9fa;
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-tabs__nav) {
  border: none;
}

:deep(.el-tabs__item) {
  color: #303133 !important;
  font-weight: 600;
  font-size: 14px;
  padding: 0 20px;
  transition: all 0.3s ease;
}

:deep(.el-tabs__item:hover) {
  color: #409eff !important;
  background: rgba(64, 158, 255, 0.1);
}

:deep(.el-tabs__item.is-active) {
  color: #409eff !important;
  background: rgba(64, 158, 255, 0.1);
  font-weight: 700;
}

:deep(.el-tabs__active-bar) {
  background-color: #409eff;
  height: 3px;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tree) {
  background: transparent;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f8f9fa;
  transform: translateX(2px);
}

:deep(.el-tree-node__expand-icon) {
  color: #409eff;
  transition: all 0.3s ease;
}

:deep(.el-tree-node__expand-icon:hover) {
  color: #409eff;
  transform: scale(1.1);
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-checkbox__input.is-focus .el-checkbox__inner) {
  border-color: #409eff;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  background: #fff;
  transition: all 0.3s ease;
  min-height: 40px;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  background: #fff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
  background: #fff;
}

:deep(.el-select) {
  width: 200px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .permission-control-container {
    padding: 15px;
  }

  .page-header {
    margin-bottom: 15px;
    padding: 15px;
  }

  .permission-management-container {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .permission-control-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 10px;
    padding: 15px;
  }

  .role-selection {
    flex-direction: column;
    align-items: stretch;
  }

  .user-simulation {
    flex-direction: column;
    align-items: stretch;
  }

  .tree-header {
    flex-direction: column;
    gap: 10px;
  }

  .tree-actions {
    flex-wrap: wrap;
  }

  .permission-test {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  }

  .menu-test {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }


}

@media (max-width: 480px) {
  .permission-control-container {
    padding: 8px;
  }

  .page-header {
    padding: 12px;
  }

  .permission-management-container {
    padding: 8px;
  }

  .tree-actions {
    gap: 4px;
  }

  .tree-actions .el-button {
    padding: 6px 10px;
    font-size: 12px;
  }
}



/* 滚动条样式 */
.permission-control-container::-webkit-scrollbar {
  width: 8px;
}

.permission-control-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.permission-control-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.permission-control-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>